<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="年级" prop="deptId">
        <!-- <el-input v-model="queryParams.deptId" placeholder="请输入年级" clearable @keyup.enter="handleQuery" /> -->
        <el-tree-select v-model="queryParams.deptId" :data="enabledDeptOptions"
          :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择归属年级"
          check-strictly default-expand-all style="width: 200px;" />
      </el-form-item>
      <el-form-item label="班级" prop="postId">
        <!-- <el-input v-model="queryParams.postId" placeholder="请输入班级" clearable @keyup.enter="handleQuery" /> -->
        <el-select v-model="queryParams.postId" placeholder="请选择班级" clearable style="width: 200px;">
          <el-option v-for="item in postIdList" :key="item.postId" :label="item.postName" :value="item.postId" />
        </el-select>
      </el-form-item>
      <el-form-item label="星期" prop="dayOfWeek">
        <el-select v-model="queryParams.dayOfWeek" placeholder="请选择星期" clearable style="width: 200px;">
          <el-option v-for="dict in week_number" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="学科" prop="subjectId">
        <!-- <el-input v-model="queryParams.subjectId" placeholder="请输入学科" clearable @keyup.enter="handleQuery" /> -->
        <el-select v-model="queryParams.subjectId" placeholder="请选择学科" clearable style="width: 200px;">
          <el-option v-for="item in subjectIdList" :key="item.subjectId" :label="item.subjectName"
            :value="item.subjectId" />
        </el-select>
      </el-form-item>
      <el-form-item label="教师" prop="teacherId">
        <el-select v-model="queryParams.teacherId" placeholder="请选择教师" clearable style="width: 200px;">
          <el-option v-for="item in teacherList" :key="item.userId" :label="item.nickName" :value="item.userId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['manage:course:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['manage:course:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['manage:course:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['manage:course:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="课程ID" align="center" prop="courseId" />
      <el-table-column label="年级" align="center" key="deptName" prop="dept.deptName" />
      <el-table-column label="班级" align="center" prop="postId">
        <template #default="scope">
          <span>
            {{postIdList.find(item => item.postId === scope.row.postId)?.postName || '未知'}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="星期" align="center" prop="dayOfWeek">
        <template #default="scope">
          <dict-tag :options="week_number" :value="scope.row.dayOfWeek" />
        </template>
      </el-table-column>
      <el-table-column label="课次" align="center" prop="classOrder">
        <template #default="scope">
          <span>第{{ scope.row.classOrder }}节</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" />
      <el-table-column label="结束时间" align="center" prop="endTime" />
      <el-table-column label="学科" align="center" prop="subjectId">
        <template #default="scope">
          <span>
            {{subjectIdList.find(item => item.subjectId === scope.row.subjectId)?.subjectName || '未知'}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="教师" align="center" prop="teacherId">
        <template #default="scope">
          <span>
            {{teacherList.find(item => item.userId === scope.row.teacherId)?.nickName || '未知'}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:course:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:course:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改课程管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="courseRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="年级" prop="deptId">
          <el-tree-select v-model="form.deptId" :data="enabledDeptOptions"
            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择归属年级"
            check-strictly default-expand-all />
        </el-form-item>
        <el-form-item label="班级" prop="postId">
          <!-- <el-input v-model="form.postId" placeholder="请输入班级" /> -->
          <el-select v-model="form.postId" placeholder="请选择班级" clearable>
            <el-option v-for="item in postIdList" :key="item.postId" :label="item.postName" :value="item.postId" />
          </el-select>
        </el-form-item>
        <el-form-item label="星期" prop="dayOfWeek">
          <el-select v-model="form.dayOfWeek" placeholder="请选择星期">
            <el-option v-for="dict in week_number" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课次" prop="classOrder">
          <el-input v-model="form.classOrder" placeholder="请输入课次" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <!-- <el-date-picker clearable v-model="form.startTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择开始时间">
          </el-date-picker> -->
          <el-time-picker clearable v-model="form.startTime" value-format="HH:mm" format="HH:mm" placeholder="请选择开始时间">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <!-- <el-date-picker clearable v-model="form.endTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择结束时间">
          </el-date-picker> -->
          <el-time-picker clearable v-model="form.endTime" value-format="HH:mm" format="HH:mm" placeholder="请选择开始时间">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="学科" prop="subjectId">
          <!-- <el-input v-model="form.subjectId" placeholder="请输入学科" /> -->
          <el-select v-model="form.subjectId" placeholder="请选择学科" clearable>
            <el-option v-for="item in subjectIdList" :key="item.subjectId" :label="item.subjectName"
              :value="item.subjectId" />
          </el-select>
        </el-form-item>
        <el-form-item label="教师" prop="teacherId">
          <el-select v-model="form.teacherId" placeholder="请选择教师" clearable>
            <el-option v-for="item in teacherList" :key="item.userId" :label="item.nickName" :value="item.userId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Course">
import { listCourse, getCourse, delCourse, addCourse, updateCourse, allClass, allSubject } from "@/api/manage/course";
import { deptTreeSelect, allTeacher } from "@/api/system/user";

const { proxy } = getCurrentInstance();
const { week_number } = proxy.useDict('week_number');

const courseList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: null,
    postId: null,
    dayOfWeek: null,
    subjectId: null,
    teacherId: null,
  },
  rules: {
    deptId: [
      { required: true, message: "年级不能为空", trigger: "blur" }
    ],
    postId: [
      { required: true, message: "班级不能为空", trigger: "blur" }
    ],
    dayOfWeek: [
      { required: true, message: "星期不能为空", trigger: "change" }
    ],
    classOrder: [
      { required: true, message: "课次不能为空", trigger: "blur" }
    ],
    startTime: [
      { required: true, message: "开始时间不能为空", trigger: "blur" }
    ],
    endTime: [
      { required: true, message: "结束时间不能为空", trigger: "blur" }
    ],
    subjectId: [
      { required: true, message: "学科不能为空", trigger: "blur" }
    ],
    teacherId: [
      { required: true, message: "教师不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询课程管理列表 */
function getList() {
  loading.value = true;
  listCourse(queryParams.value).then(response => {
    courseList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    courseId: null,
    deptId: null,
    postId: null,
    dayOfWeek: null,
    classOrder: null,
    startTime: null,
    endTime: null,
    subjectId: null,
    teacherId: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("courseRef");
}

const postIdList = ref([]);

// 班级下拉框数据，获取所有班级
function getAllClass() {
  allClass().then(response => {
    postIdList.value = response.data;
    // console.log(postIdList.value);
  });
}
getAllClass();

const subjectIdList = ref([]);

// 学科下拉框数据，获取所有学科
function getAllSubject() {
  allSubject().then(response => {
    subjectIdList.value = response.data;
    // console.log(subjectIdList.value);
  });
}
getAllSubject();

const teacherList = ref([]);

// 教师下拉框数据，获取所有教师
function getAllTeacher() {
  allTeacher().then(response => {
    teacherList.value = response.rows;
    // console.log(teacherList.value);
  });
}
getAllTeacher();


const deptOptions = ref(undefined);
const enabledDeptOptions = ref(undefined);

/** 查询年级下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
    enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
  });
};
getDeptTree()

/** 过滤禁用的年级 */
function filterDisabledDept(deptList) {
  return deptList.filter(dept => {
    if (dept.disabled) {
      return false;
    }
    if (dept.id == 101) {
      return false;
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children);
    }
    return true;
  });
};


/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.courseId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加课程管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _courseId = row.courseId || ids.value
  getCourse(_courseId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改课程管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["courseRef"].validate(valid => {
    if (valid) {
      if (form.value.courseId != null) {
        updateCourse(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCourse(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _courseIds = row.courseId || ids.value;
  proxy.$modal.confirm('是否确认删除课程管理编号为"' + _courseIds + '"的数据项？').then(function () {
    return delCourse(_courseIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/course/export', {
    ...queryParams.value
  }, `course_${new Date().getTime()}.xlsx`)
}

getList();
</script>
